public without sharing class SalesOrderController {

	public String msg {get; private set;} 
	public Boolean isErr {get; private set;} 
	public Boolean isSuccess {get ; private set;}
    public class ControllerException extends Exception {}
    public String dataJson {get; private set;} 
	public String saveJson {get;  set;} 
	public String searchJson {get;  set;} 
	private  String sealflag;
	public  SalesOrderApplication__c soa {get;private set ;}
	public string backId {get;set;}
    public String  SpecificRequirements {get;private set;}
	private Map<String,DataUtil.SObjectBean> stageObjectMap ; 
	private Boolean isNew ; 
	public string type {get;private set;} 
    public String buyerId {get;private set;}

    private String parentId ;
	public void setNil(){
    	dataJson = '{}';
    	saveJson = '[]';
    	searchJson = '{}';
    }
    public SalesOrderController() {
        stageObjectMap = new  Map<String,DataUtil.SObjectBean>();

        backId = System.currentPageReference().getParameters().get('id');
        type = System.currentPageReference().getParameters().get('recordtype');
        soa = new SalesOrderApplication__c();
        isNew = false;
    }
    //设置错误
    private void setError(String message){
    	isErr = true;
      throw new ControllerException(message);

    }
    public void init(){


    	try {
    	    Account acc = null ; 
    	    if(Id.valueOf(backId).getSobjecttype() == SalesOrderApplication__c.Sobjecttype ){//编辑 

    	    	soa = [select Id,RecordType.DeveloperName,SpecialPrice__c ,SpecificRequirements__c,
                RebateDeduction__c,TotalDiscount__c ,PriceExecutionMode__c,Buyer__c,Buyer__r.ParentId  ,Status__c,ReturnSlip__c,ReturnSlip__r.Name  
                from SalesOrderApplication__c where Id =: backId];
    	    	type = soa.RecordType.DeveloperName;
                parentId = soa.Buyer__r.ParentId;
    	    	if(soa.Status__c == '审批中' || soa.Status__c == '已批准' )setError('海外订单'+soa.Status__c +' ,不能修改!');
                SpecificRequirements = soa.SpecificRequirements__c;

    	    }else if(Id.valueOf(backId).getSobjecttype() == Account.Sobjecttype){
    	    	acc  = [select Id ,ParentId ,Name, NCReceiver__c ,NCReceiverPhone__c ,ConsigneeMailbox__c, NCReceiveAddress__c ,
                Receiver__c, InvoiceAddress__c, TicketCollectTelephone__c,SpecificRequirements__c 
                 from Account where Id =: backId];
    	    	soa.Buyer__c = backId;
                parentId = acc.ParentId;
    	    	isNew = true ; 
                SpecificRequirements = acc.SpecificRequirements__c;
    	    }else{

    	    	setError('页面打开错误!');

    	    }
            buyerId = soa.Buyer__c;
    	    User u = [select Id, Subcompany__c from User where Id =: UserInfo.getUserId()];
    	   	sealflag  =  'Y-'+ ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(u.SubCompany__c);   
			Map<String,Object> dataMap = new Map<String,Object>();
    		
    		dataMap.put('searchObject',getSearchObject()); 

    		dataMap.put('detail',getDetails()); 
            dataMap.put('reslip',getRelip()); 


    		dataMap.put('SalesOrderDetailed__c',getSODField()); 

           // dataMap.put('ReturnSlip__c',getReslipField()); 

    		 //字段
	    	 Map<String,Set<String>> fieldsmap = getFields();
	    	 System.debug('SalesOrderController==>'+fieldsMap);
	    	 //字段详情
	    	 Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
	    	 System.debug('SalesOrderController==>'+fbMap);
	    	
	    	//字段赋值
	    	 Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
	    	  
              Map<String,String > comFields = new Map<String,String>();
              comFields.put('InvoiceContact__c', 'Receiver__c');
              comFields.put('InvoiceAddress__c', 'InvoiceAddress__c');
              comFields.put('ReceiverContactInformation__c', 'TicketCollectTelephone__c');
              comFields.put('Consignee__c', 'NCReceiver__c');
              comFields.put('ConsigneeContactInformation__c', 'NCReceiverPhone__c');
              comFields.put('ConsigneeMailbox__c', 'ConsigneeMailbox__c');
              comFields.put('ReceivingAddress__c', 'NCReceiveAddress__c');

	    	 if(isNew){
               // 收票 Receiver__c, InvoiceAddress__c, TicketCollectTelephone__c
                // InvoiceContact__c   InvoiceAddress__c ReceiverContactInformation__c
                //收货 Consignee__c ConsigneeContactInformation__c ConsigneeMailbox__c ReceivingAddress__c
                //NCReceiver__c  NCReceiverPhone__c ConsigneeMailbox__c NCReceiveAddress__c
	    	 	for(String objname : fields.keySet() ){

		    	 	 for(DataUtil.FieldBean f : fields.get(objname)){
                        if(comFields.containsKey(f.name))f.value = acc.get(comFields.get(f.name));
		    	 	 	if(f.name == 'Buyer__c'){
		    	 	 		Map<String,Object> vMap  = new Map<String,Object>();
			    			vMap.put('Name', acc.Name );
			    			vMap.put('Id', acc.Id  );

			    			f.value = vMap;
			    			//break;
		    	 	 	}

		    	 	 }
		    	 }
	    	 }
	    	 
             System.debug('SalesOrderController==>'+stageObjectMap);

	 		dataMap.put('base',fields);
    		dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 


			dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap),'UTF-8');



    	}catch (Exception e) {
    	    
    	     ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));

    	}
    	

    }
     public Map<String,Set<String>>  getFields(){
    	Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
    	
    		DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

    		sb.title ='';
    		sb.objname = 'SalesOrderApplication__c';
    		sb.stype = DataUtil.getSObjectType('SalesOrderApplication__c');
    		sb.idvalue = soa.Id ;
    		sb.type = 'base';
    		sb.condition = ' where Id =\''+soa.Id+'\'';
    		stageObjectMap.put('SalesOrderApplication__c',sb );

    		Set<String>  fields = new Set<String>{'TransactionTerms__c','PaymentMethod__c','InvoiceAddress__c','InvoiceContact__c','ReceiverContactInformation__c','Consignee__c','ConsigneeMailbox__c','ConsigneeContactInformation__c','ReceivingAddress__c','DestinationPort__c','ShippingType__c'};
    		if(soa.RecordType.DeveloperName == 'ReagentSalesOrders' || type == 'ReagentSalesOrders' ){
    			fields.add('PriceExecutionMode__c');
    			fields.add('TotalDiscount__c');
    			//fields.add('ReturnSlip__c');

    		}else{
                fields.add('SpecialPrice__c');
            }
    		fieldsMap.put('SalesOrderApplication__c', fields);
    	
    	return fieldsMap;
    }

    public void save (){

    	msg = '';
    	Map<String,Object> saveMap  = (Map<String,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	Map<String,Object> baseMap = (Map<String,Object>)saveMap.get('base');
    	DataUtil.SObjectBean sb  = stageObjectMap.get('SalesOrderApplication__c');

		SObject so = sb.stype.newSObject();
		Map<String,Set<String>> fieldsMap = getFields();
		Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(sb.stype,fieldsMap.get('SalesOrderApplication__c'));
		for(String field : baseMap.keySet()){

			so.put(field, DataUtil.dataHandler(baseMap.get(field),fbeanMap.get(field).type.toUpperCase() ));
		}
		if(!isNew) so.put('Id', soa.Id );
        if(isNew) so.put('SpecificRequirements__c', SpecificRequirements);
        if(isNew) so.put('Buyer__c', soa.Buyer__c);
		if(isNew) so.put('RecordTypeId',  type == 'ReagentSalesOrders' ? Utils.getRecordTypeIdByDevNameAndObjName('ReagentSalesOrders', 'SalesOrderApplication__c') : Utils.getRecordTypeIdByDevNameAndObjName('InstrumentSalesOrders', 'SalesOrderApplication__c'));




    	List<Object> saveList = (List<Object>)saveMap.get('detial');

    	List<SalesOrderDetailed__c> sodList = new List<SalesOrderDetailed__c>();

    	for(Object o : saveList){
    		Map<String,Object> mo = (Map<String,Object>)o ; 
    		if(mo.get('productId') == null){
    			msg = '产品数据异常!';
    			return;
    		}

    		SalesOrderDetailed__c sod = new SalesOrderDetailed__c();
    		sod.Product__c = DataUtil.getStringValue(mo.get('productId'));
    		sod.ExecutionPriceNew__c = DataUtil.getDecimalValue(mo.get('exeprice'));
    		sod.PriceExecutionMode__c = DataUtil.getStringValue(mo.get('exemethod'));
    		sod.No__c = DataUtil.getDecimalValue(mo.get('num'));
    		sod.BuyingPrice__c = DataUtil.getDecimalValue(mo.get('buyprice'));
    		sod.PrototypePrice__c = DataUtil.getDecimalValue(mo.get('prototypeprice'));
    		sod.UnitPrice__c = DataUtil.getDecimalValue(mo.get('price'));
    		 sod.Deduction__c = DataUtil.getDecimalValue(mo.get('deprice'));

    		if(!isNew)sod.SalesOrderApplication__c  = soa.Id ; 
    		sodList.add(sod);



    	}
        Set<String> ordSet = new Set<String>();
        List<Object> resList = (List<Object>)saveMap.get('reslip');
        List<OrderRebateForm__c> rrList = new List<OrderRebateForm__c>();
        for(Object o : resList){
            Map<String,Object> mo = (Map<String,Object>)o ; 
            if(mo.get('rid') == null){
                msg = '返利单数据异常!';
                return;
            }

            OrderRebateForm__c  ord = new OrderRebateForm__c();
            ord.Id = DataUtil.getStringValue(mo.get('id'));
            ord.RebatefForm__c =  DataUtil.getStringValue(mo.get('rid'));
            ord.RebateAmount__c = DataUtil.getDecimalValue(mo.get('cost'));
            ord.Order__c = DataUtil.getStringValue(mo.get('oid'));
            rrList.add(ord);
            if(ord.Id != null )ordSet.add(ord.Id);

        }

    	SavePoint sp = Database.setSavepoint();
    	try {

    		 upsert so ; 
    		 if(isNew){
    		 	for(SalesOrderDetailed__c sod : sodList){

    		 		sod.SalesOrderApplication__c = so.Id ; 
    		 	}

    		 }

             for(OrderRebateForm__c orr : rrList ){
                orr.Order__c = so.Id;
             }

            System.debug(ordSet);
            System.debug([select Id from OrderRebateForm__c where Order__c =: so.Id and Id not in: ordSet  ]);
             delete [select Id from OrderRebateForm__c where Order__c =: so.Id and Id not in: ordSet  ];

    	    delete [select Id from SalesOrderDetailed__c where SalesOrderApplication__c =:soa.Id ];

            System.debug(sodList);


    	    if(sodList.size() > 0 )insert sodList;
            System.debug(rrList);
            if(!rrList.isEmpty() ) upsert rrList;

    	    isSuccess = true; 
    	    backId = so.Id; 
    	    msg = '保存成功!';
    	}
    	catch (Exception e) {
    	    msg = '保存失败!'+e.getMessage();
    	    if(isNew){
    	    	so.put('Id', null);
    	    	backId = soa.Buyer__c;
    	    }

    	}
    	

    }

    private  Map<Id,PriceList__c> getPriceListMap (Set<Id> pset,String accId ){
        Map<Id,PriceList__c> prLMap = new Map<Id,PriceList__c> ();

        for(PriceList__c pl :[select Id,Product__c ,CooperativePrice__c ,BuyingPrice__c, Remarks__c,PrototypePrice__c  from PriceList__c where Product__c in: pset  and Account__c =: accId ]){             
            prLMap.put(pl.Product__c , pl);
        }
        return prLMap;

    }


    private List<SalesOrderDetailedBean>   getDetails(){

    	List<SalesOrderDetailedBean> tmp = new List<SalesOrderDetailedBean>();
        List<SalesOrderDetailed__c>sdL = [select Id ,Product__r.ProductName__c , No__c , Product__r.Spec__c,
        Product__r.Brand__c,Product__r.NCCode__c,Product__r.SerialNo__c,Product__r.Unit__c,Deduction__c,
        UnitPrice__c, ExecutionPriceNew__c ,BuyingPrice__c, PrototypePrice__c,PriceExecutionMode__c


         from SalesOrderDetailed__c where SalesOrderApplication__c =: backId];

         Set<Id> pids = new Set<Id>();
        for(SalesOrderDetailed__c sd : sdL){
            pids.add(sd.Product__c);

        }

          Map<Id,PriceList__c> prLMap = getPriceListMap(pids, parentId == null ? soa.Buyer__c : parentId );

		for(SalesOrderDetailed__c sd : sdL){
			
			tmp.add(new SalesOrderDetailedBean(sd,prLMap.get(sd.Product__c)));

		}

		return tmp; 

    }
    private List<ReslipBean> getRelip(){
        List<ReslipBean> tmp = new List<ReslipBean>();

        List<OrderRebateForm__c>sdL = [select Id ,RebatefForm__r.Name , RebatefForm__r.Distributor__r.Name , RebatefForm__r.ReturnAmountUsed__c,
        RebatefForm__r.Policy__c,RebatefForm__r.PreferentialAmount__c,RebatefForm__r.ReturnBalance__c,RebatefForm__r.ConditionsUse__c,RebatefForm__c,
        Order__c,RebateAmount__c

         from OrderRebateForm__c where Order__c =: backId];
      
        for(OrderRebateForm__c sd : sdL){
            
            tmp.add(new ReslipBean(sd));

        }

        return tmp; 

    }

    private Map<String,List<DataUtil.FieldBean>> getSearchObject(){
    	Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

    	Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Product__c.SObjecttype, new Set<String>{'ProductName__c','Brand__c','Spec__c','SerialNo__c','Category0__c','Category1__c','NCCode__c'} );
    	searchMap.put('Product__c', proMap.values());
    	return searchMap;
    }
    private Map<String,List<DataUtil.FieldBean>> getSODField(){
    	Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

    	Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(SalesOrderDetailed__c.SObjecttype, new Set<String>{'PriceExecutionMode__c'} );
    	searchMap.put('SalesOrderDetailed__c', proMap.values());
    	return searchMap;
    }
     private Map<String,List<DataUtil.FieldBean>> getReslipField(){
        Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

        Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(ReturnSlip__c.SObjecttype, new Set<String>{'Name','Distributor__r.Name','ConditionsUse__c','ReturnAmountUsed__c','Policy__c','PreferentialAmount__c','ReturnBalance__c'} );
        searchMap.put('ReturnSlip__c', proMap.values());
        return searchMap;
    }

    @RemoteAction
    public static List<SalesOrderDetailedBean>  matchProduct(List<String> nccodes,String accId ){
        List<SalesOrderDetailedBean> tmp = new List<SalesOrderDetailedBean>();
        Map<Id,PriceList__c > pMap  = new Map<Id,PriceList__c>();
        for(PriceList__c p : [select Id ,BuyingPrice__c,PrototypePrice__c,CooperativePrice__c,Product__r.Unit__c,Product__r.ProductName__c ,
            Product__r.SerialNo__c ,Product__r.Model__c, Product__r.Brand__c ,Product__r.Spec__c,Product__r.Category0__c,
            Product__r.NCCode__c ,Product__r.Category1__c ,Product__r.SealCompany__c from PriceList__c
         where Product__r.NCCode__c in: nccodes and Account__c =: accId and Product__r.Category0__c !='仪器'   ]){
            
            tmp.add(new SalesOrderDetailedBean(p));
        }

        return tmp; 
    }


    public void searchSlip(){
        
        Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));

        String sql = ' select Id ,Name ,Distributor__r.Name,ReturnAmountUsed__c,Policy__c,PreferentialAmount__c ,ReturnBalance__c ,ConditionsUse__c from ReturnSlip__c where  Distributor__c = \''+ (parentId == null ?  soa.Buyer__c : parentId )+'\'  and ReturnBalance__c > 0  ';

        if(String.isBlank(DataUtil.getStringValue(searchMap.get('name'))) == false) sql += ' and Name like \'%'+DataUtil.getStringValue(searchMap.get('name'))+'%\' ';

       if(String.isBlank(DataUtil.getStringValue(searchMap.get('accName'))) == false) sql += ' and Distributor__r.Name like \'%'+DataUtil.getStringValue(searchMap.get('accName'))+'%\' ';

        sql += ' limit 200 ';
        List<ReslipBean>  tmp = new  List<ReslipBean>();
       
        for(ReturnSlip__c p : Database.query(sql)){

            tmp.add(new ReslipBean(p ));
        }
        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    public void search(){
    	dataJson = '[]';

    	Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));

    	String sql = ' select Id ,BuyingPrice__c,PrototypePrice__c,CooperativePrice__c,Product__r.Unit__c,Product__r.ProductName__c ,Product__r.SerialNo__c ,Product__r.Model__c, Product__r.Brand__c ,Product__r.Spec__c,Product__r.Category0__c,Product__r.NCCode__c ,Product__r.Category1__c ,Product__r.SealCompany__c from PriceList__c where Account__c =\''+(parentId == null ?  soa.Buyer__c : parentId )+'\' ';
    	if(type == 'ReagentSalesOrders')sql += ' and Product__r.Category0__c !=\'仪器\' ';
    	if(type == 'InstrumentSalesOrders')sql += ' and Product__r.Category0__c =\'仪器\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('ProductName__c'))) == false) sql += ' and Product__r.ProductName__c like \'%'+DataUtil.getStringValue(searchMap.get('ProductName__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Brand__c'))) == false) sql += ' and Product__r.Brand__c like \'%'+DataUtil.getStringValue(searchMap.get('Brand__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Spec__c'))) == false) sql += ' and Product__r.Spec__c like \'%'+DataUtil.getStringValue(searchMap.get('Spec__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('SerialNo__c'))) == false) sql += ' and Product__r.SerialNo__c like \'%'+DataUtil.getStringValue(searchMap.get('SerialNo__c'))+'%\' ';
 
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category0__c'))) == false) sql += ' and Product__r.Category0__c like \'%'+DataUtil.getStringValue(searchMap.get('Category0__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category1__c'))) == false) sql += ' and Product__r.Category1__c like \'%'+DataUtil.getStringValue(searchMap.get('Category1__c'))+'%\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('NCCode__c'))) == false) sql += ' and Product__r.NCCode__c like \'%'+DataUtil.getStringValue(searchMap.get('NCCode__c'))+'%\' ';

    	sql += ' limit 200 ';
    	List<SalesOrderDetailedBean>  tmp = new  List<SalesOrderDetailedBean>();
    	Map<Id,Product__c > pMap  = new Map<Id,Product__c>();
    	/*for(PriceList__c p: Database.query(sql)){
            if(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)) continue; 
			pMap.put(p.Id , p);
    	}*/
   		for(PriceList__c p : Database.query(sql)){
   			tmp.add(new SalesOrderDetailedBean(p ));
   		}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    public class SalesOrderDetailedBean{

    	public String productId ;
    	public String productName ; 
    	public String spec ; 
    	public String serialno ;
    	public String nccode ; 
    	public String unit ; 
    	public String brand ; 
    	public Decimal price ; 
    	public Decimal deprice ; 
    	public Decimal exeprice ; 
    	public Decimal num ; 
    	public String cate0; 
    	public String cate1; 
    	public Decimal prototypeprice;
        public Decimal buyprice ; 
        public String exemethod; 

        
    	public SalesOrderDetailedBean(SalesOrderDetailed__c sd ,PriceList__c pl ){

    		productName = sd.Product__r.ProductName__c;
    		productId = sd.Product__c;
    		spec = sd.Product__r.Spec__c;
    		serialno = sd.Product__r.SerialNo__c;
    		nccode = sd.Product__r.NCCode__c;
    		unit = sd.Product__r.Unit__c;
    		brand = sd.Product__r.Brand__c;
    		deprice = sd.Deduction__c;
    		price = sd.UnitPrice__c;
            if(pl != null) price = pl.CooperativePrice__c;
    		exeprice = sd.ExecutionPriceNew__c ; 
    		num = sd.No__c;
    		prototypeprice = sd.PrototypePrice__c;
            if(pl != null) prototypeprice = pl.PrototypePrice__c;
    		buyprice = sd.BuyingPrice__c;
            if(pl != null) buyprice = pl.BuyingPrice__c;
    		exemethod = sd.PriceExecutionMode__c;

    	}
    	public SalesOrderDetailedBean(PriceList__c sd ){

    		productName = sd.Product__r.ProductName__c;
    		productId = sd.Product__c;
    		spec = sd.Product__r.Spec__c;
    		serialno = sd.Product__r.SerialNo__c;
    		nccode = sd.Product__r.NCCode__c;
    		unit = sd.Product__r.Unit__c;
    		brand = sd.Product__r.Brand__c;
    		cate0 = sd.Product__r.Category0__c;
    		cate1 = sd.Product__r.Category1__c;
    		price = sd.CooperativePrice__c;
    		prototypeprice = sd.PrototypePrice__c;
    		buyprice = sd.BuyingPrice__c;
    	}

    }

    public class ReslipBean{

        public String name ; //返利单号
        public String id; //明细id 
        public String accName ;//
        public Decimal used;
        public String policy;
        public Decimal total;
        public Decimal rest;
        public String condition ;
        public String rid;//返利单id
        public String oid ;//订单id;
        public Decimal cost;//本次使用

        public ReslipBean (ReturnSlip__c r ){
            name = r.Name;
            accName = r.Distributor__r.Name;
            used = r.ReturnAmountUsed__c;
            policy = r.Policy__c;
            total = r.PreferentialAmount__c;
            rest = r.ReturnBalance__c;
            condition = r.ConditionsUse__c;

            rid = r.Id;
        }

        public ReslipBean (OrderRebateForm__c  r ){
            name = r.RebatefForm__r.Name;
            accName = r.RebatefForm__r.Distributor__r.Name;
            used = r.RebatefForm__r.ReturnAmountUsed__c;
            policy = r.RebatefForm__r.Policy__c;
            total = r.RebatefForm__r.PreferentialAmount__c;
            rest = r.RebatefForm__r.ReturnBalance__c;
            condition = r.RebatefForm__r.ConditionsUse__c;
            rid = r.RebatefForm__c ;
            id = r.id;
            oid = r.Order__c;
            cost = r.RebateAmount__c;

        }


    }

}